<?php

namespace App\Http\Middleware\Api;

use App\Exceptions\BusinessException;
use App\Helpers\Libraries\TimeLibrary;
use App\Models\Log\RequestLog as RequestLogModel;
use Closure;
use Illuminate\Http\Request;

class RequestLog
{
    /**
     * Handle an incoming request.
     * 日志中间件
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     * @throws BusinessException
     */
    public function handle(Request $request, Closure $next)
    {
        $log = new RequestLogModel(); // 日志表
        $log->url = $request->url();
        $log->ip = $request->getClientIp ();
        $log->params = json_encode($request->all(), JSON_UNESCAPED_UNICODE);
        $log->save();
        $response = $next($request);
        if ($rep = $response->getContent()){
            $log->update ([
                'response_params' => $rep,
                'user_id' => $request->user() ? $request->user()->id : 0,
                'duration' => TimeLibrary::getRequestMicroTime(),
            ]);
        }
        return $response;
    }
}
